<template>
  <textarea :class="classProp" ref="observe" v-model="text" ></textarea>
</template>

<script>
  export default {
    name: "TextArea",
    props: ['classProp','defaultText'],
    data() {
      return {
        text: ''
      }
    },
    methods: {
      resize() {
        let returnText = this.text;
        this.$emit('sendVal', this.textAreaTo(returnText))
        let textArea = this.$refs.observe
        textArea.style.height = 'auto';
        textArea.style.height = textArea.scrollHeight + 'px';
      },
      delayedResize() {
        window.setTimeout(this.resize, 0);
      },
      textAreaTo(str){
        var reg = new RegExp("\n", "g")
        var regSpace = new RegExp(" ", "g")

        str = str.replace(reg,"<br>")
        str = str.replace(reg,"<br/>")
        str = str.replace(regSpace,"&nbsp;")

        return str
      },
      toTextArea(str){
        var reg = new RegExp("<br>","g")
        var reg2 = new RegExp("<br/>","g")
        var regSpace = new RegExp("&nbsp;","g")

        str = str.replace(reg, "\n");
        str = str.replace(reg2, "\n");
        str = str.replace(regSpace, "")

        return str
      }
    },
    mounted() {
      let textArea = this.$refs.observe
      textArea.addEventListener('change', this.resize, false);
      textArea.addEventListener('cut', this.delayedResize, false);
      textArea.addEventListener('paste', this.delayedResize, false);
      textArea.addEventListener('drop', this.delayedResize, false);
      textArea.addEventListener('keydown', this.delayedResize, false);
      this.text = this.defaultText ? this.toTextArea(this.defaultText) : ''
      this.delayedResize()

    }
  }
</script>

<style scoped>

</style>
